from django import forms
from django.db.models import ObjectDoesNotExist
from comment.models import Comment
from .bootstrap import BootStrapForm
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey


class CommentForm(forms.ModelForm):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    content_object = GenericForeignKey('content_type', 'object_id')

    parent_comment_id = forms.IntegerField(widget=forms.HiddenInput(attrs={'id': 'parent_comment_id'}))

    body = forms.CharField(
        label='',
        min_length=1,
        max_length=150,
        error_messages={
            'min_length': "输入您的评论",
            'max_length': "您的评论超字数啦！"},
        widget=forms.Textarea(attrs={'class': "form-control",
                                     'aria-describedby': 'button-addon2',
                                     'placeholder': "请写下你的评论......",
                                     'rows': "1",
                                     'data-emojiable': "true", })
    )

    def __init__(self, *args, **kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(CommentForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Comment
        fields = ['body']

    def clean(self):
        # 判断用户是否登录
        if self.user.is_authenticated:
            self.cleaned_data['user'] = self.user
        else:
            raise forms.ValidationError('用户尚未登录')

        # 评论对象验证
        content_type = self.cleaned_data['content_type']
        object_id = self.cleaned_data['object_id']
        try:
            model_class = ContentType.objects.get(model=content_type).model_class()
            model_obj = model_class.objects.get(pk=object_id)
            self.cleaned_data['content_object'] = model_obj
        except ObjectDoesNotExist:
            raise forms.ValidationError('评论对象不存在')

        return self.cleaned_data

    def clean_parent_comment_id(self):
        parent_comment_id = self.cleaned_data['parent_comment_id']
        if parent_comment_id < 0:
            raise forms.ValidationError('回复出错')
        elif parent_comment_id == 0:
            self.cleaned_data['parent'] = None
        elif Comment.objects.filter(pk=parent_comment_id).exists():
            self.cleaned_data['parent'] = Comment.objects.get(pk=parent_comment_id)
        else:
            raise forms.ValidationError('回复出错')
        return parent_comment_id

















